package com.wdhcr.weixin;


import com.wdhcr.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/*
 * @description: 处理博客系统接入微信公众号的controller
 * @author: wdhcr
 * @dateTime: 2020/3/16 20:00
 */
@Controller

public class WeixinController {

    @Autowired
    private WxUtil wxUtil;

    /**
     * @description: 接收微信服务器的controller，验证签名
     * @params: [request]
     * @return: java.lang.String
     * @author: wdhcr
     * @dateTime: 2019/12/30 21:32
     */
    @CrossOrigin
    @GetMapping(value = "/get_token")
    @ResponseBody
    public String getToken(HttpServletRequest request) {
        //获取微信服务器返回的字段数据
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        //对微信服务器发送的数据进行签名验证完成微信接入
        if (wxUtil.check(signature, timestamp, nonce, echostr)) {
            System.out.println("接入成功");
            //当验证成功后，返回echostr
            return echostr;
        } else {
            System.out.println("接入失败");
        }
        //否则返回null
        return null;
    }

    /**
     * @description: 接收用户post请求，和发送的数据并返回对应的数据
     * @params: [request]
     * @return: java.lang.String
     * @author: wdhcr
     * @dateTime: 2019/12/30 21:32
     */
    @CrossOrigin
    @PostMapping(value = "/get_token")
    @ResponseBody
    public String postToken(HttpServletRequest request) throws IOException {

        //获取用户发送的数据包
        ServletInputStream is = request.getInputStream();

        //将微信服务器的xml数据包转换成map集合
        Map<String, String> requestMap = wxUtil.parseRequest(request.getInputStream());
        String respXml = null;
        System.out.println("requestMap+:" + requestMap);
        if (requestMap != null) {
//            System.out.println(requestMap + "--------------controller");
            respXml = wxUtil.getRespose(requestMap);
        }
        return respXml;
    }


    /**
     * @description: 页面请求返回带参数的二维码的ticket
     * @params: []
     * @return: java.lang.String
     * @author: wdhcr
     * @dateTime: 2019/12/31 17:26
     */
    @CrossOrigin
    @GetMapping(value = "/getTicket")
    @ResponseBody
    public String getTicket(@RequestParam(value = "sceneId") int sceneId) {
        System.out.println(sceneId);
//        System.out.println(wxUtil.getQrCodeTicket(sceneId));

        //sceneid是前端请求获取ticket时传入的这里设置
        // 的该页面的时间戳sceneid临时二维码限制32位非0整型，永久限制为最大值为100000
        //生成带有参数sceneid临时二维码的ticket


        return wxUtil.getQrCodeTicket(sceneId);

    }

}
